﻿using KuMaoPlayer.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WMPLib;

namespace KuMaoPlayer
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }
        private void FormMain_Load(object sender, EventArgs e)
        {
            music_player.settings.autoStart = false;
            // music_player.URL = @"E:\KuGou\林俊杰 - 裂缝中的阳光.flac";
            var config = ConfigFile.LoadOrCreateFile("config.test");
            string str = config["local"];
            string[] sArray = str.Split('^');
            for (int i = 1; i < sArray.Length; i++)
            {
                listpath.Add(sArray[i]);
                listBox_musicList.Items.Add(Path.GetFileName(sArray[i]));
            }
            string lrc = config["lrc"];
            string[] lrcArray = lrc.Split('^');
            for (int i = 1; i < lrcArray.Length; i++)
            {
                lrcpath.Add(lrcArray[i]);
            }
        }
        // 存储文件的路径
        List<string> listpath = new List<string>();
        List<string> lrcpath = new List<string>();
        /// <summary>
        /// 导入音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_add_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = @"C\";
                ofd.Filter = "所有文件|*.*|本地音乐文件|*.flac|MP3文件|*.mp3";
                ofd.Title = "选择本地音乐文件";
                ofd.Multiselect = true;
                ofd.ShowDialog();

                // 获得在文本框中选择文件的全路径
                string[] path = ofd.FileNames;
                for (int i = 0; i < path.Length; i++)
                {
                    bool b = true;
                    foreach (string s in listpath)
                    {
                        if (s == path[i])
                        {
                            b = false; break;
                        }
                    }
                    // 将音乐文件的全路径存储到泛型集合
                    if (b)
                    {
                        listpath.Add(path[i]);
                        // 将音乐文件的文件名存储到listbox中
                        listBox_musicList.Items.Add(Path.GetFileName(path[i]));
                        lrcpath.Add("none");
                    }
                }
            }
            catch
            {

            }
        }
        /// <summary>
        /// 双击播放音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_musicList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (listBox_musicList.Items.Count == 0)
                {
                    MessageBox.Show("请先导入音乐文件");
                    return;
                }

                var current_mp3_url = listpath[listBox_musicList.SelectedIndex];

                form_Current.change_album(current_mp3_url);

                music_player.URL = listpath[listBox_musicList.SelectedIndex];
                music_player.Ctlcontrols.play();
                pictureBox_play.Tag = 2;
                pictureBox_play.Image = Resources.暂停;
                trackBar_time.Value = 0;
                // label_information.Text = music_player.currentMedia.duration.ToString();
                // 播放按钮状态切换代码
                // ...
                // label2.Text = music_player.currentMedia.duration.ToString();
            }
            catch
            {

            }
        }
        /// <summary>
        /// 点击下一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_next_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前选中项的索引
                int index = listBox_musicList.SelectedIndex;
                // 清空所有选中项的索引
                listBox_musicList.SelectedIndices.Clear();
                if (pictureBox_mode.Tag.ToString() == "3") {
                    Random rd = new Random();
                    int i = rd.Next(0, listBox_musicList.Items.Count-1);
                    if (i == index) index++; else index = i;
                    if (index == listBox_musicList.Items.Count)
                    {
                        index = 0;
                    }
                }
                else { 
                    index++;
                    if (index == listBox_musicList.Items.Count)
                    {
                        index = 0;
                    }
                }
                // 将改变后的索引重新赋值给当前播放的索引
                listBox_musicList.SelectedIndex = index;

                music_player.URL = listpath[index];
                music_player.Ctlcontrols.play();
                pictureBox_play.Tag = 2;
                pictureBox_play.Image = Resources.暂停;
                trackBar_time.Value = 0;
            }
            catch
            {

            }
        }
        /// <summary>
        /// 点击上一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_last_Click(object sender, EventArgs e)
        {
            try
            {
                //pictureBox_play.Tag.ToString() == "1"
                // 获取当前选中项的索引
                int index = listBox_musicList.SelectedIndex;
                // 清空所有选中项的索引
                listBox_musicList.SelectedIndices.Clear();
                if (pictureBox_mode.Tag.ToString() == "3")
                {
                    Random rd = new Random();
                    int i = rd.Next(0, listBox_musicList.Items.Count - 1);
                    if (i == index) index--; else index = i;
                    if (index < 0)
                    {
                        index = listBox_musicList.Items.Count - 1;
                    }
                }
                else
                {
                    index--;
                    if (index < 0)
                    {
                        index = listBox_musicList.Items.Count - 1;
                    }
                }
                // 将改变后的索引重新赋值给当前播放的索引
                listBox_musicList.SelectedIndex = index;

                music_player.URL = listpath[index];
                music_player.Ctlcontrols.play();
                pictureBox_play.Tag = 2;
                pictureBox_play.Image = Resources.暂停;
                trackBar_time.Value = 0;
            }
            catch
            {

            }
        }
        /// <summary>
        /// 打开子界面函数
        /// </summary>
        private Form activeFrom = null;
        private void openSubFrom(Form subFrom)
        {
            if (activeFrom != null)
                activeFrom.Hide();
            activeFrom = subFrom;
            subFrom.TopLevel = false;
            subFrom.FormBorderStyle = FormBorderStyle.None;
            subFrom.Dock = DockStyle.Fill;
            panel_subForm.Controls.Add(subFrom);
            panel_subForm.Tag = subFrom;
            subFrom.BringToFront();
            subFrom.Show();
        }
        /// <summary>
        /// 播放或者暂停按键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        bool b = true;
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try
            {
                if (pictureBox_play.Tag.ToString() == "1")
                {
                    // 获取选中的歌曲
                    if (b)     // 如果当前播放和点击索引项不同，重头播放
                    {
                        music_player.URL = listpath[listBox_musicList.SelectedIndex];
                    }
                    music_player.Ctlcontrols.play();
                    pictureBox_play.Tag = 2;
                    pictureBox_play.Image = Resources.暂停;
                }
                else if (pictureBox_play.Tag.ToString() == "2")
                {
                    music_player.Ctlcontrols.pause();
                    pictureBox_play.Tag = 1;
                    pictureBox_play.Image = Resources.播放;
                    b = false;
                }
            }
            catch
            {
                MessageBox.Show("请先选择一首音乐！！！");
            }
        }
        /// <summary>
        /// 点击静音或者放音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_volume_Click(object sender, EventArgs e)
        {
            if (pictureBox_volume.Tag.ToString() == "1")
            {
                // 点击静音
                music_player.settings.mute = true;
                // 显示静音图片
                pictureBox_volume.Image = Resources.静音;
                pictureBox_volume.Tag = 2;
            }
            else if (pictureBox_volume.Tag.ToString() == "2")
            {
                // 点击放音
                music_player.settings.mute = false;
                // 显示放音图片
                pictureBox_volume.Image = Resources.声音;
                pictureBox_volume.Tag = 1;
            }
        }
        /// <summary>
        /// 滑轮控制音量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trackBar_volume_Scroll(object sender, EventArgs e)
        {
            music_player.settings.volume = trackBar_volume.Value;
        }
        /// <summary>
        /// 打开最近播放子界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label2_Click(object sender, EventArgs e)
        {
            openSubFrom(form_Recent);
            //panel_recentList.BackColor = System.Drawing.Color.White;
        }
        /// <summary>
        /// 打开我的喜欢子界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label_favoriteList_Click(object sender, EventArgs e)
        {
            openSubFrom(form_Mylist);
        }
        /// <summary>
        /// 打开当前播放子界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label_currentList_Click(object sender, EventArgs e)
        {
            openSubFrom(form_Current);
        }
        /// <summary>
        /// 批处理鼠标悬停事件--对应控件背景色修改为白色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseEnter_mulControls(object sender, EventArgs e)
        {
            if (sender == pictureBox_add)
            {
                pictureBox_add.BackColor = System.Drawing.Color.White;
            }
            else if (sender == label_localList || sender == pictureBox_localListImage)
            {
                label_localList.BackColor = System.Drawing.Color.White;
                pictureBox_localListImage.BackColor = System.Drawing.Color.White;
            }
            else if (sender == label_favoriteList || sender == pictureBox_favoriteListImage)
            {
                label_favoriteList.BackColor = System.Drawing.Color.White;
                pictureBox_favoriteListImage.BackColor = System.Drawing.Color.White;
            }
            else if (sender == label_recentList || sender == pictureBox_recentListImage)
            {
                label_recentList.BackColor = System.Drawing.Color.White;
                pictureBox_recentListImage.BackColor = System.Drawing.Color.White;
            }
            else if (sender == label_currentList || sender == pictureBox_currentListImage)
            {
                label_currentList.BackColor = System.Drawing.Color.White;
                pictureBox_currentListImage.BackColor = System.Drawing.Color.White;
            }
            else if (sender == pictureBox_play)
            {
                pictureBox_play.BackColor = System.Drawing.Color.White;
            }
            else if (sender == pictureBox_mode)
            {
                pictureBox_mode.BackColor = System.Drawing.Color.White;
            }
            else if (sender == pictureBox_next)
            {
                pictureBox_next.BackColor = System.Drawing.Color.White;
            }
            else if (sender == pictureBox_last)
            {
                pictureBox_last.BackColor = System.Drawing.Color.White;
            }
            else if (sender == pictureBox_volume)
            {
                pictureBox_volume.BackColor = System.Drawing.Color.White;
            }
        }
        /// <summary>
        /// 批处理鼠标离开事件-相应控件背景色恢复为透明
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseLeave_mulControl(object sender, EventArgs e)
        {
            if (sender == pictureBox_add)
            {
                pictureBox_add.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == label_localList || sender == pictureBox_localListImage)
            {
                label_localList.BackColor = System.Drawing.Color.Transparent;
                pictureBox_localListImage.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == label_favoriteList || sender == pictureBox_favoriteListImage)
            {
                label_favoriteList.BackColor = System.Drawing.Color.Transparent;
                pictureBox_favoriteListImage.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == label_recentList || sender == pictureBox_recentListImage)
            {
                label_recentList.BackColor = System.Drawing.Color.Transparent;
                pictureBox_recentListImage.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == label_currentList || sender == pictureBox_currentListImage)
            {
                label_currentList.BackColor = System.Drawing.Color.Transparent;
                pictureBox_currentListImage.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == pictureBox_play)
            {
                pictureBox_play.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == pictureBox_next)
            {
                pictureBox_next.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == pictureBox_mode)
            {
                pictureBox_mode.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == pictureBox_last)
            {
                pictureBox_last.BackColor = System.Drawing.Color.Transparent;
            }
            else if (sender == pictureBox_volume)
            {
                pictureBox_volume.BackColor = System.Drawing.Color.Transparent;
            }
        }
        /// <summary>
        /// 右键删除选中项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除此音乐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 先删除列表中的选中项
            // 获取删除歌曲数量
            int count = listBox_musicList.SelectedItems.Count;
            for (int i = 0; i < count; i++)
            {
                // 先删除集合中歌曲
                listpath.RemoveAt(listBox_musicList.SelectedIndex);
                // 再删除列表框中的索引项
                listBox_musicList.Items.RemoveAt(listBox_musicList.SelectedIndex);
            }
        }
        /// <summary>
        /// 右键更改歌词路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 更改歌词路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            { 
                //MessageBox.Show("1");
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = @"C\";
                ofd.Filter = "所有文件|*.*|LRC文件|*.lrc";
                ofd.Title = "选择本地歌词文件";
                ofd.Multiselect = false;
                ofd.ShowDialog();

                // 获得在文本框中选择文件的全路径
                string path = ofd.FileName;
                //MessageBox.Show(listBox_musicList.SelectedIndex.ToString());
                lrcpath.RemoveAt(listBox_musicList.SelectedIndex);
                lrcpath.Insert(listBox_musicList.SelectedIndex, path);
            }
            catch
            {

            }
        }
        /// <summary>
        /// 点击添加到我喜欢列表  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        Form_Mylist form_Mylist = new Form_Mylist();
        Form_Current form_Current = new Form_Current();
        Form_Recent form_Recent = new Form_Recent();
        int countn = 0;
        private void 添加到我喜欢ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBox_musicList_SelectedIndexChanged(listBox_musicList);
        }
        private void listBox_musicList_SelectedIndexChanged(ListBox listBox_musicList)
        {
            try
            {
                form_Mylist.AddSongList(listBox_musicList.SelectedItem.ToString());
            }
            catch
            {
                MessageBox.Show("添加失败，请重新尝试");
            }

        }
        /// <summary>
        /// timer事件-处理歌曲/歌词进度和时间显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                // 如果播放器状态为正在播放
                if (music_player.playState == WMPLib.WMPPlayState.wmppsPlaying)
                {
                    form_Current.label1.Text = Path.GetFileName(listpath[listBox_musicList.SelectedIndex]);
                    // 将进度条的最大值设置为当前歌曲的长度
                    trackBar_time.Maximum = (int)music_player.currentMedia.duration + 1;
                    countn++;
                    if (countn == 10) { trackBar_time.Value += 1; countn = 0; }
                    
                    /* 歌曲时间显示测试代码
                    label_information.Text = music_player.currentMedia.duration.ToString() +
                        "\r\n" + music_player.currentMedia.durationString + "\r\n" +
                        music_player.Ctlcontrols.currentPosition.ToString() +
                        "\r\n" + music_player.Ctlcontrols.currentPositionString;*/
                    // 进度条前后时间label.Text显示
                    label_currtime.Text = music_player.Ctlcontrols.currentPositionString;
                    label_endtime.Text = music_player.currentMedia.durationString;

                    //这几行可以写在定时器外面
                    int totalHeight = form_Current.listShowSongLrc.Height;
                    //设置显示的每一项的高度
                    int height = form_Current.listShowSongLrc.ItemHeight = 30;
                    //需要显示多少行歌词
                    int num = totalHeight / height;
                    //显示歌词为奇数行，方便获取当前歌词行
                    num = num % 2 == 1 ? num : num - 1;//MessageBox.Show(num.ToString());
                    num = 21;
                    if (lrcpath[listBox_musicList.SelectedIndex] != "none")
                    {
                        form_Current.listShowSongLrc.Items.Clear();// MessageBox.Show(lrcpath[listBox_musicList.SelectedIndex]);
                        Lrc lrc = Lrc.InitLrc(lrcpath[listBox_musicList.SelectedIndex]);
                        //MessageBox.Show(music_player.Ctlcontrols.currentPosition.ToString());
                        double time = music_player.Ctlcontrols.currentPosition;
                        /*int i = 0;
                        for (i = 0; i < lrc.LrcWord.Count; i++)
                        {
                            var item = lrc.LrcWord.ElementAt(i);
                            var itemKey = item.Key;
                            if (itemKey > time) break;
                        }i--;
                        lrc.LrcWord = */
                        for (int i = 0; i < lrc.LrcWord.Count-1; i++)
                        {
                            //歌曲当前位置

                            //歌曲唱的过程中，显示当前歌词的前后各num/2行
                            if (lrc.LrcWord.ElementAt(i).Key<time && lrc.LrcWord.ElementAt(i+1).Key >= time)
                            {
                                //清除只能够放在if里面，放在if外面基本上看不到歌词
                                //MessageBox.Show(i.ToString());
                                form_Current.listShowSongLrc.Items.Clear();

                                for (int x = (i - num / 2); x <= (i + num / 2); x++)
                                {
                                    form_Current.listShowSongLrc.Items.Add(x < 0 || x >= lrc.LrcWord.Count ? "" : lrc.LrcWord.ElementAt(x).Value);
                                }
                            }

                        }
                        // 歌曲唱完以后，后面显示为空
                        if (lrc.LrcWord.ElementAt(lrc.LrcWord.Count - 1).Key < time)
                        {
                            form_Current.listShowSongLrc.Items.Clear();
                            for (int x = -num / 2; x <= num / 2; x++)
                            {
                                form_Current.listShowSongLrc.Items.Add(x <= 0 ? lrc.LrcWord.ElementAt(lrc.LrcWord.Count - 1 + x).Value : "");
                            }
                        }
                        //歌词还没有开始显示的时候，中间显示歌名，后面显示前几行歌词
                        if (lrc.LrcWord.ElementAt(0).Key >= time)
                        {
                            form_Current.listShowSongLrc.Items.Clear();
                            for (int x = -num / 2; x <= num / 2; x++)
                            {
                                form_Current.listShowSongLrc.Items.Add(x > 0 ? lrc.LrcWord.ElementAt(x).Value : "");
                            }
                        }
                        /*for (int j = 0; j < form_Current.listShowSongLrc.Items.Count; j++)
                        {
                            form_Current.listShowSongLrc.SelectedIndex = j;
                        }*/

                    }
                    else
                    {
                        form_Current.listShowSongLrc.Items.Clear();
                        for (int x = 0; x < num; x++)
                        {
                            form_Current.listShowSongLrc.Items.Add(x != num / 2 ? "" : "---未  找  到  歌  词---");
                        }
                        
                    }

                    // 定义两个变量为双进度currentTime和endTime
                    double d1 = double.Parse(music_player.currentMedia.duration.ToString());
                    double d2 = double.Parse(music_player.Ctlcontrols.currentPosition.ToString()) + 1;  // 精度不够

                    // 如果播放完毕(判断条件歌曲当前时间>=总时间)，则下一曲
                    // 这里采用的方法是当前歌曲最后不到一秒精度的时间直接卡过去，使得当前时间大于歌曲总时长，
                    // 此时执行下一首播放
                    //if (music_player.currentMedia.durationString == music_player.Ctlcontrols.currentPositionString)
                    if (d1 <= d2)
                    {
                        // 播放完毕，将播放的歌曲和时间记录到最近播放列表
                        form_Recent.listView_recent.Items.Add(Path.GetFileName(listpath[listBox_musicList.SelectedIndex]));
                        form_Recent.listView_recent.Items[0].SubItems.Add(DateTime.Now.ToString());
                        // 获取当前选中项的索引
                        int index = listBox_musicList.SelectedIndex;
                        // 清空所有选中项的索引
                        listBox_musicList.SelectedIndices.Clear();
                        if (pictureBox_mode.Tag.ToString() == "3")
                        {
                            Random rd = new Random();
                            int i = rd.Next(0, listBox_musicList.Items.Count - 1);
                            if (i == index) index++; else index = i;
                            if (index == listBox_musicList.Items.Count)
                            {
                                index = 0;
                            }
                        }
                        else if(pictureBox_mode.Tag.ToString() == "1")
                        {
                            index++;
                            if (index == listBox_musicList.Items.Count)
                            {
                                index = 0;
                            }
                        }
                        // 将改变后的索引重新赋值给当前播放的索引
                        listBox_musicList.SelectedIndex = index;

                        music_player.URL = listpath[index];
                        music_player.Ctlcontrols.play();
                        pictureBox_play.Tag = 2;
                        pictureBox_play.Image = Resources.暂停;

                        // 播放下一首时将滚轮回0
                        trackBar_time.Value = 0;
                    }
                }
                else
                {
                    form_Current.label1.Text = " ";
                }
            }
            catch
            {

            }

        }
        /// <summary>
        /// 歌曲播放进度拖动事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trackBar_time_Scroll(object sender, EventArgs e)
        {
            music_player.Ctlcontrols.currentPosition = trackBar_time.Value;
        }
        /// <summary>
        /// 关闭提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            var config = ConfigFile.LoadOrCreateFile("config.test");
            config["local"] = null;
            foreach (string s in listpath)
            {
                //MessageBox.Show(s);
                config["local"] = config["local"] + "^" + s;
            }
            config["lrc"] = null;
            foreach (string s in lrcpath)
            {
                config["lrc"] = config["lrc"] + "^" + s;
            }
            DialogResult result = MessageBox.Show("你确定要关闭吗！", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                e.Cancel = false;  //点击OK   
            }
            else
            {
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 播放模式切换---列表循环/单曲循环/随机播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_mode_Click(object sender, EventArgs e)
        {
            try
            {
                if (pictureBox_mode.Tag.ToString() == "1")
                {
                    pictureBox_mode.Tag = 2;
                    pictureBox_mode.Image = Resources.首页_播放模式_单曲循环__1_;
                }
                else if (pictureBox_mode.Tag.ToString() == "2")
                {
                    pictureBox_mode.Tag = 3;
                    pictureBox_mode.Image = Resources.首页_播放模式_随机播放__1_;
                }
                else if (pictureBox_mode.Tag.ToString() == "3")
                {
                    pictureBox_mode.Tag = 1;
                    pictureBox_mode.Image = Resources.首页_播放模式_列表循环__1_;
                }
            }
            catch
            {
                
            }
        }
    }
}
